package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.SkuHasStockTo;
import com.atguigu.common.to.member.MemberRespTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.to.order.OrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    PaymentInfoService paymentInfoService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {

        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespTo memberRespTo = LoginInterceptor.threadLocal.get();
        //取出当前线程的数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //1.
            //在其他线程中放入自己的数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespTo.getId());
            confirmVo.setAddress(address);
        }, executor);


        CompletableFuture<Void> itemFuture = CompletableFuture.runAsync(() -> {
            //在其他线程中放入自己的数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //2.
            List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem(memberRespTo.getId());
            confirmVo.setItem(currentUserCartItem);
        }, executor).thenRunAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = confirmVo.getItem();
            List<Long> skuIds = items.stream().map(e -> e.getSkuId()).collect(Collectors.toList());
            List<SkuHasStockTo> data = wareFeignService.getHasStockByskuIds(skuIds);
            if (data != null) {
                Map<Long, Boolean> collect = data.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
                confirmVo.setStocks(collect);
            }
        });

        CompletableFuture<Void> integrationFuture = CompletableFuture.runAsync(() -> {
            //3.
            RequestContextHolder.setRequestAttributes(requestAttributes);
            Integer integration = memberRespTo.getIntegration();
            confirmVo.setIntegration(integration);
        }, executor);


        //4.设置防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespTo.getId(), token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);

        CompletableFuture.allOf(integrationFuture, itemFuture, addressFuture).get();


        return confirmVo;
    }

    //    @GlobalTransactional
    @Transactional
    @Override
    public SubmitRespVo submitOrder(OrderSubmitVo submitVo) throws NoStockException {
        SubmitRespVo respVo = new SubmitRespVo();
        orderSubmitVoThreadLocal.set(submitVo);

        MemberRespTo memberRespTo = LoginInterceptor.threadLocal.get();
        //1.验证令牌
        String orderToken = submitVo.getOrderToken();
        respVo.setCode(0);
        //验证通过[保证令牌 删除 的 原子性]
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        // 原子验证和删除
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class)
                , Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespTo.getId())
                , orderToken);
        if (result == 0L) {
            //令牌验证失败
            respVo.setCode(1);
            return respVo;
        } else {
            //验证成功
            //创建订单信息
            OrderCreateTo order = CreateOrder();
            //验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = submitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //验价成功
                //3.保存订单
                saveOrder(order);
                //4.库存锁定,只要有异常就回滚订单数据
                //需要订单号 ， 所有订单项
                WareSkuLockVo lockVo = new WareSkuLockVo();
                List<OrderItemVo> locks = order.getOrderItems().stream().map(e -> {
                    //封装成传输的vo
                    OrderItemVo orderItemVo = new OrderItemVo();

                    orderItemVo.setSkuId(e.getSkuId());
                    orderItemVo.setCount(e.getSkuQuantity());
                    orderItemVo.setTitle(e.getSkuName());

                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);

                lockVo.setOrderSn(order.getOrder().getOrderSn());

                R r = wareFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    //锁定成功
                    respVo.setOrder(order.getOrder());
                    //TODO 订单创建成功 发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return respVo;
                } else {
                    //锁定失败
                    respVo.setCode(3);
                    throw new NoStockException(order.getOrder().getId());
                }
            } else {
                respVo.setCode(2);
                return respVo;
            }
        }
    }

    private void saveOrder(OrderCreateTo order) {
        //保存订单数据
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);

    }


    private OrderCreateTo CreateOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //生成订单号
//        String orderSn = UUID.randomUUID().toString().substring(0, 6);
        String orderSn = IdWorker.getTimeId();
        //创建订单号
        OrderEntity orderEntity = buildOrder(orderSn);

        //获得所有订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        //验价  计算价格相关
        OrderEntity order = computePrice(orderEntity, itemEntities);

        orderCreateTo.setOrderItems(itemEntities);

        orderCreateTo.setOrder(order);
        //TODO 线程释放
        orderSubmitVoThreadLocal.remove();
        return orderCreateTo;
    }

    private OrderEntity computePrice(OrderEntity orderEntity, List<OrderItemEntity> items) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal Promotion = new BigDecimal("0.0");
        BigDecimal Coupon = new BigDecimal("0.0");
        BigDecimal Integration = new BigDecimal("0.0");
        Integer giftIntegration = 0;
        Integer giftGrowth = 0;
        //订单的总额
        for (OrderItemEntity item : items) {
            Promotion = Promotion.add(item.getCouponAmount());
            Coupon = Coupon.add(item.getPromotionAmount());
            Integration = Integration.add(item.getIntegrationAmount());
            total = total.add(item.getRealAmount());
            giftIntegration = item.getGiftIntegration();
            giftGrowth = item.getGiftGrowth();
        }
        //1.订单，价格相关
        orderEntity.setTotalAmount(total);
        //设置应付总额（加上运费）
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //设置促销金额
        orderEntity.setPromotionAmount(Promotion);
        //设置优惠金额
        orderEntity.setCouponAmount(Coupon);
        //设置积分优惠
        orderEntity.setIntegrationAmount(Integration);

        //设置积分信息
        orderEntity.setIntegration(giftIntegration);
        orderEntity.setGrowth(giftGrowth);
        orderEntity.setDeleteStatus(0);
        return orderEntity;
    }

    /**
     * 通过订单号创建实体类
     *
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setMemberId(LoginInterceptor.threadLocal.get().getId());
        orderEntity.setMemberUsername(LoginInterceptor.threadLocal.get().getUsername());
        orderEntity.setOrderSn(orderSn);
        //获取收获地址信息
        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();
        R r = wareFeignService.getFare(orderSubmitVo.getAddrId());
        if (r.getCode() == 0) {
            FareVo fare = r.getData(new TypeReference<FareVo>() {
            });
            //设置运费
            orderEntity.setFreightAmount(fare.getFare());
            MemberAddressVo address = fare.getAddress();
            //设置订单的收货人信息
            orderEntity.setReceiverDetailAddress(address.getDetailAddress());
            orderEntity.setReceiverName(address.getName());
            orderEntity.setReceiverCity(address.getCity());
            orderEntity.setReceiverPhone(address.getPhone());
            orderEntity.setReceiverPostCode(address.getPostCode());
            orderEntity.setReceiverProvince(address.getProvince());
            orderEntity.setReceiverRegion(address.getRegion());
        }

        //设置订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);

        return orderEntity;
    }

    /**
     * 构建所有订单项
     * 获取订单项信息，获取redis购物车被选中的项
     *
     * @param orderSn
     * @return
     */
    @Override
    public List<OrderItemEntity> buildOrderItems(String orderSn) {

        List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem(LoginInterceptor.threadLocal.get().getId());
        if (currentUserCartItem != null && currentUserCartItem.size() > 0) {

            List<OrderItemEntity> itemList = currentUserCartItem.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());

            return itemList;
        } else {
            return null;
        }
    }

    /**
     * 构建每一个订单项
     *
     * @param cartItem
     * @return
     */
    @Override
    public OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity entity = new OrderItemEntity();
        //1.订单信息 √

        //2.商品的Spu信息
        Long skuId = cartItem.getSkuId();
        SpuInfoVo spuInfoVo = productFeignService.getSpuInfoBySkuId(skuId);
        entity.setSpuId(spuInfoVo.getId());
        entity.setSpuName(spuInfoVo.getSpuName());
        entity.setSpuBrand(spuInfoVo.getBrandName());
        entity.setCategoryId(spuInfoVo.getCatalogId());

        //3.商品的Sku信息
        String skuAttrsStr = org.springframework.util.StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        entity.setSkuId(cartItem.getSkuId());
        entity.setSkuName(cartItem.getTitle());
        entity.setSkuPic(cartItem.getImage());
        entity.setSkuPrice(cartItem.getPrice());
        entity.setSkuAttrsVals(skuAttrsStr);
        entity.setSkuQuantity(cartItem.getCount());
        //4.商品的优惠信息[暂时不做]

        //5.商品的积分信息
        entity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        entity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //6.订单项的价格信息
        entity.setPromotionAmount(new BigDecimal("0"));
        entity.setCouponAmount(new BigDecimal("0"));
        entity.setIntegrationAmount(new BigDecimal("0"));
        BigDecimal orign = new BigDecimal(entity.getSkuPrice().toString()).multiply(new BigDecimal(entity.getSkuQuantity().toString()));
        BigDecimal real = orign.subtract(entity.getPromotionAmount()).subtract(entity.getCouponAmount()).subtract(entity.getIntegrationAmount());
        entity.setRealAmount(real);

        return entity;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    /**
     * 关闭订单
     *
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        OrderEntity orderEntity = this.getById(entity.getId());
        OrderEntity update = new OrderEntity();
        if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            //关单
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);//覆盖式
            //解锁成功
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            log.info("发送解锁成功的消息给库存");
            try {
                //TODO 保证消息百分百发出去，每一个消息都做一个日志记录
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception e) {
                //TODO 将没发送的消息重新发送，
            }
        }
    }

    /**
     * 获取当前订单的支付信息
     *
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);

        payVo.setTotal_amount(String.valueOf(order.getPayAmount().setScale(2, BigDecimal.ROUND_UP)));
        payVo.setBody("谷粒商城");//订单备注
        payVo.setOut_trade_no(order.getOrderSn());//订单号
        List<OrderItemEntity> orderItems = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        payVo.setSubject("谷粒商城->" + orderItems.get(0).getSkuName());//订单的主题
        return payVo;
    }

    /**
     * 查询当前用户的所有订单信息，分页查询
     * @param params
     * @return
     */
    @Override
    public PageUtils queryWithItem(Map<String, Object> params) {
        MemberRespTo memberRespTo = LoginInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespTo.getId()).orderByDesc("id")
        );
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(list);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1.保存交易流水
        PaymentInfoEntity payment = new PaymentInfoEntity();
        //2.对拷属性(字段不对应)
        payment.setAlipayTradeNo(vo.getTrade_no());
        payment.setOrderSn(vo.getOut_trade_no());
        payment.setPaymentStatus(vo.getTrade_status());
//        payment.setCallbackTime(new Date(vo.getNotify_time()));

        paymentInfoService.save(payment);

        //3.修改订单状态信息
        if(vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")){
            String orderSn = vo.getOut_trade_no();//订单号
            this.baseMapper.updateOrderStat(orderSn,1);
        }
        return null;
    }

    @Override
    public void createSecOrder(SeckillOrderTo seckillOrder) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal(seckillOrder.getNum()));
        orderEntity.setPayAmount(multiply);

        this.save(orderEntity);

        //TODO 保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(seckillOrder.getOrderSn());
        itemEntity.setSkuId(seckillOrder.getSkuId());
        itemEntity.setRealAmount(multiply);
        itemEntity.setSkuQuantity(seckillOrder.getNum());
        //TODO 通过feign来获取sku信息

        orderItemService.save(itemEntity);
    }

    @Override
    public void payOrder(String orderSn) {
        this.baseMapper.updateOrderStat(orderSn,1);
    }


}